import PermissionControl from '@/components/PermissionControl';
import { getGoodsSpecsList } from '@/services/stock-goods/api';
import { stockManageList } from '@/services/stock-goods/subApi';
import { notEmpty, showMsg } from '@/utils/utils';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, FormInstance } from 'antd';
import { useRef, useState } from 'react';

const ManageTab = (props: ManageTabProps) => {

  const { brandList, classList, goodsList } = props;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  // 规格列表
  const [specList, setSpecList] = useState<STOCKGOODSAPI.GoodsSpecsItem[]>([]);

  const columns: ProColumns<STOCKGOODSAPI.StockItem>[] = [
    {
      title: '批次号',
      dataIndex: 'batch_id',
      search: false
    },
    {
      title: '库存数量',
      dataIndex: 'inventory',
      search: false
    },
    {
      title: '商品分类',
      dataIndex: 'class_id',
      hideInTable: true,
      colSize: 3.5,
      valueType: 'select',
      fieldProps: {
        placeholder: '选择商品分类',
        options: classList,
        showSearch: true,
        filterOption: true,
      }
    },
    {
      title: '商品品牌',
      dataIndex: 'brand_id',
      hideInTable: true,
      colSize: 3.5,
      valueType: 'select',
      fieldProps: {
        placeholder: '选择商品品牌',
        options: brandList,
        showSearch: true
      }
    },
    {
      title: '商品品牌',
      dataIndex: 'brand_name',
      search: false
    },
    {
      title: '商品名称',
      dataIndex: 'goods_id',
      hideInTable: true,
      colSize: 3.5,
      valueType: 'select',
      fieldProps: form => ({
        options: goodsList,
        onChange: (value: any) => {
          form.setFieldsValue({ 'spec_id': null });
          if (!value) {
            setSpecList([]);
            return;
          }
          fetchGoodsSpecList(value);
        }
      })
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      search: false
    },
    {
      title: '商品规格',
      dataIndex: 'specs_id',
      hideInTable: true,
      colSize: 2.5,
      valueType: 'select',
      hideInSearch: !notEmpty(specList),
      fieldProps: () => ({
        options: (specList || []).map(item => ({
          label: item.specs_name,
          value: item.specs_id
        })),
        showSearch: true
      })
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      search: false
    },
    {
      title: '规格编号',
      dataIndex: 'specs_no',
      className: 'wordbreak',
      search: false
    },
    {
      title: '规格描述',
      dataIndex: 'specs_name',
      ellipsis: true,
      search: false
    }
  ];

  // 商品规格
  const fetchGoodsSpecList = async (goods_id: string) => {
    try {
      const data: STOCKGOODSAPI.GoodsSpecsItemList = await getGoodsSpecsList({ goods_id, current: 1, pageSize: 10000 });
      setSpecList(data.record_list || []);
    } catch (error: any) {
      console.log('error', error)
      showMsg(error?.data?.errmsg);
    }
  }

  return (
    <ProTable<STOCKGOODSAPI.StockItem, STOCKGOODSAPI.StockItem & STOCKGOODSAPI.GoodsItem & { begin_date?: string; end_date?: string; } & COMMON.PageParams>
      actionRef={actionRef}
      formRef={formRef}
      rowKey="approval_id"
      bordered
      columns={columns}
      search={{
        span: 2,
        collapsed: false,
        collapseRender: false,
        style: { paddingRight: 8 },
        optionRender: () => ([
          <PermissionControl key="search" action_id="200204001">
            <Button type="primary" onClick={() => formRef.current?.submit()}>
              查询
            </Button>
          </PermissionControl>
        ])
      }}
      request={async (params) => {
        try {
          const res = await stockManageList(params);
          return {
            success: true,
            data: res.record_list,
            total: res.sum_record_num
          };
        } catch (error: any) {
          showMsg(error?.data?.errmsg);
          return { success: false, data: [] };
        }
      }}
      options={false}
      pagination={{ showQuickJumper: true }}
    />
  );
};

export default ManageTab;

interface ManageTabProps {
  classList: COMMON.SelectOption[]
  brandList: COMMON.SelectOption[]
  goodsList: COMMON.SelectOption[]
}
